package com.lonely.tasks;

import com.lonely.common.annotation.RedisLock;
import com.lonely.deliver.service.IOrderDeliverSynchronizedTaskService;
import com.lonely.order.service.IOrderService;
import com.lonely.order.support.synchronizer.SynchronizedOrderDeliverThreadLocal;
import com.lonely.order.support.synchronizer.service.SynchronizerOrderDeliverService;
import com.lonely.order.threadlocals.OrderSynchronizedThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author: 黄志标
 * @date: 2025/6/18 14:46
 * @description: 订单相关定时任务
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private SynchronizerOrderDeliverService synchronizerOrderDeliverService;

    @Autowired
    private IOrderDeliverSynchronizedTaskService orderDeliverSynchronizedTaskService;


    /**
     * 每小时执行一次（整点触发）
     */
//    @Scheduled(cron = "0 0 * * * ?")
    @RedisLock(key = "'task:executeOrderSynchronizedTask'", waitTime = 0)
//    @Scheduled(cron = "0/30 * * * * ?")
    public void executeOrderSynchronizedTask() {
        log.debug("触发同步订单接口...");
        OrderSynchronizedThreadLocal.taskTrigger();
        try {
            this.orderService.synchronizerTodayOrder();
        } finally {
            OrderSynchronizedThreadLocal.clear();
            log.debug("触发同步订单接口执行结束...");
        }
    }

    /**
     * 同步订单发货单数据
     * 每小时执行一次（整点触发）
     */
//    @Scheduled(cron = "0 0 * * * ?")
    @RedisLock(key = "'task:executeSynchronizedOrderDeliverTask'", waitTime = 0)
//    @Scheduled(cron = "0/30 * * * * ?")
    public void executeSynchronizedOrderDeliverTask() {
        log.debug("触发同步订单发货单接口...");
        try {
            this.synchronizerOrderDeliverService.synchronizerOrderDeliver();
        } finally {
            SynchronizedOrderDeliverThreadLocal.remove();
            log.debug("触发同步订单发货单接口执行结束...");
        }
    }

    /**
     * 订单发货单同步任务 定时任务
     * 每10分钟执行一次
     */
    @RedisLock(key = "'task:executeSynchronizedOrderDeliverSynchronizedTask'", waitTime = 0)
    @Scheduled(cron = "0 */10 * * * ?")
    public void executeSynchronizedOrderDeliverSynchronizedTask() {
        log.debug("触发同步订单发货单同步任务接口...");
        try {
            this.orderDeliverSynchronizedTaskService.doingSynchronizedTask();
        } finally {
            SynchronizedOrderDeliverThreadLocal.remove();
            log.debug("触发同步订单发货单同步任务接口执行结束...");
        }
    }


}
